﻿//process.stdout.write(process.argv[2]+"\r\n");
//process.exit();
var argv=process.argv;
var bindhost=argv[2];
var bindport=argv[3];
var targethost=argv[4];
var targetport=argv[5];
var net=require('net');
var loglevel=2;
var firadio=require('firadio');
//===================================
process.title='TCP端口转发器['+bindport+']TO['+targethost+':'+targetport+']';
var stdin=process.openStdin();
stdin.setEncoding('binary');
stdin.on('data',function(chunk){
	var chunk_len=chunk.length-2;
	chunk=firadio.gbk_to_utf8(chunk.substr(0,chunk_len));
	if(chunk=='exit'){
		process.exit();
	}
	process.stdout.write('data:['+chunk+']('+chunk_len+")\r\n");
});
stdin.on('end',function(){
	process.stdout.write('end');
});
//===================================
var server=net.createServer(function(serverc){
	var conndatetime=+new Date();
	if(loglevel>=2)firadio.log('[转发器]有连接进入！');
	var client=net.connect(targetport,targethost,function(){
		if(loglevel>=2)firadio.log('成功连接到[目标服务器]！');
		//client.write('world!\r\n');
	});
	client.on('data',function(data){
		if(loglevel>=2)firadio.log('接到来自[目标服务器]的数据!');
		try{
			serverc.write(data);//向[客户端]发送数据
		}catch(e){
			if(loglevel>=2)firadio.log('向[客户端]发送数据时报错'+e);
		}
	});
	client.on('end',function(){
		if(loglevel>=2)firadio.log('[目标服务器]关闭连接！');
		serverc.end();//关闭客户端的连接
	});
	client.on('error',function(){
		if(loglevel>=1)firadio.log('[目标服务器]连接不上！');
	});
	serverc.on('end',function(){
		if(loglevel>=2)firadio.log('有个[客户端]断开！');
		client.end();//断开目标服务器
	});
	serverc.on('error',function(){
		if(loglevel>=1)firadio.log('[serverc-on-error]向[客户端]发送数据时报错！');
	});
	serverc.on('data',function(data){
		if(loglevel>=2)firadio.log('接到来自[客户端]的数据！');
		//firadio.log('转发器有数据传入'+data.toString());
		try{
			client.write(data);//向[目标服务器]发送数据
		}catch(e){
			if(loglevel>=2)firadio.log('向[目标服务器]发送数据时报错'+e);
		}
	});
	//serverc.pipe(serverc);
});
server.on('error',function(data){
	var errorinfo=data.toString();
	if(errorinfo=='Error: listen EADDRINUSE'){
		errorinfo='监听端口被占用！';
	}
	firadio.log('转发器有错误：'+errorinfo);
	process.exit();
});
server.listen(bindport,bindhost,function(){
	firadio.log('转发器已启动！');
});
